package com.portme.client.pages;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ResizeLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.portme.client.PortmeServiceClient;
import com.portme.client.StaticFactory;
import com.portme.client.helpers.ThemeDialogBox;
import com.portme.client.interfaces.Observer;
import com.portme.shared.ClientCustomTab;
import com.portme.shared.LoginInfo;
import com.portme.shared.UserProfile;

public class AccountPage extends Composite implements Observer {
	private FlowPanel holdingPanel = new FlowPanel();
	private LoginInfo currentLogin;
	private UserProfile currentProfile;
	private TabLayoutPanel tabPanel;
	private UrlSplitted urlInfo;
	private String theme;
	
	public AccountPage(String url) {
		initWidget(holdingPanel);
		currentLogin = StaticFactory.getInstance().getCurrentUserLogin();
		
		urlInfo = decodeUrl(url);
		
		PortmeServiceClient.getInstance().getUserPortfolio(urlInfo.user, new AsyncCallback<UserProfile>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Failure : "+caught.getMessage());
			}

			@Override
			public void onSuccess(UserProfile result) {
				currentProfile = result;
				StaticFactory.getInstance().setCurrentProfile(currentProfile);
				theme = StaticFactory.getInstance().getTheme();
				createWidget();
				StaticFactory.getInstance().observeTheme(AccountPage.this);
			}
		});
	}
	
	private void createWidget() {
		RootPanel.get().addStyleName(StaticFactory.getInstance().getTheme());
		if(currentLogin != null && currentProfile != null) {
			
			HorizontalPanel headerWidget = new HorizontalPanel();
			headerWidget.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
			
			Label username;
			Anchor login;
			HorizontalPanel toolsPanel = null;
			if(currentLogin.isLoggedIn()) {
				login = new Anchor("Logout", currentLogin.getLogoutUrl());
				username = new Label("Welcome "+currentLogin.getUsername());
				
				//ToolBar for change theme.
				toolsPanel = new HorizontalPanel();
				
				if(/*currentLogin.getUsername().equals(currentProfile.getUser())*/ StaticFactory.getInstance().allowPermission()) {
					final Button changeThemeButton = new Button("Change Theme");
					changeThemeButton.addClickHandler(new ClickHandler() {
						
						@Override
						public void onClick(ClickEvent event) {
							ThemeDialogBox themeSelectorDialog = new ThemeDialogBox();
							themeSelectorDialog.showRelativeTo(changeThemeButton);
						}
					});
					toolsPanel.add(changeThemeButton);
				}
				
			} else {
				login = new Anchor("Login", currentLogin.getLoginUrl());
				username = new Label("Have a Google account? ");
			}
			
//			login = new Anchor("Logout", currentLogin.getLogoutUrl());
//			username = new Label("Welcome "+currentLogin.getUsername());
			headerWidget.add(username);
			headerWidget.add(login);
			
			
			tabPanel = new TabLayoutPanel(2.5, Unit.EM);
		    tabPanel.setAnimationDuration(500);
		    
		    tabPanel.setStylePrimaryName(theme+"-tabpanel");
		    
		    /*tabPanel.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() {
				
				@Override
				public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {
					try {
						SingleTabWidget tabWidget = (SingleTabWidget)tabPanel.getWidget(event.getItem().intValue());
						Long tabId = tabWidget.getTabId();
						if(tabId != null)
							History.newItem(""+StaticFactory.getInstance().getCurrentProfile().getUser().split("@")[0]+"/"+tabId, false);
					} catch (Exception e) {
						Window.alert(e.getMessage());
					}
				}
			});*/
		    
		    int tabToBeSelected = 0;
		    if(currentProfile != null) {
		    	for(ClientCustomTab tab : currentProfile.getTabs()) {
		    		if(urlInfo != null && urlInfo.tab != null && urlInfo.tab.equals(tab.getId())) {
	    				tabPanel.add(new SingleTabWidget(urlInfo.user, tab, urlInfo.post), tab.getTitle());
	    				tabToBeSelected = tabPanel.getWidgetCount() - 1;
		    		} else {
		    			tabPanel.add(new SingleTabWidget(urlInfo.user, tab, null), tab.getTitle());
		    		}
		    		
		    	}
		    }
		    
		    Button addTab = null;
		    if(currentLogin.isLoggedIn() && currentLogin.getUsername() != null 
		    		&& currentLogin.getUsername().equals(currentProfile.getUser())) {
				addTab = new Button("Add tab");
			    addTab.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						// TODO Auto-generated method stub
						final DialogBox addTabDialog = new DialogBox(false);
						
						final TextBox tabTitle = new TextBox();
						Button addTabButton = new Button("Add Tab", new ClickHandler() {
							
							@Override
							public void onClick(ClickEvent event) {
								
								PortmeServiceClient.getInstance().createTab(tabTitle.getText(), new AsyncCallback<ClientCustomTab>() {

									@Override
									public void onFailure(Throwable caught) {
										// TODO Auto-generated method stub
										Window.alert("Could not create tab");
									}

									@Override
									public void onSuccess(ClientCustomTab result) {
										// TODO Auto-generated method stub
										tabPanel.add(new SingleTabWidget(currentLogin.getUsername().split("@")[0], result, null), tabTitle.getText());
										addTabDialog.hide();
										tabPanel.selectTab(tabPanel.getWidgetCount()-1);
									}
								});
								
							}
						});
						
						Button closeDialog = new Button("Close", new ClickHandler() {
							
							@Override
							public void onClick(ClickEvent event) {
								// TODO Auto-generated method stub
								addTabDialog.hide();
							}
						});
						VerticalPanel panel = new VerticalPanel();
						panel.add(tabTitle);
						HorizontalPanel buttons = new HorizontalPanel();
						buttons.add(addTabButton);
						buttons.add(closeDialog);
						panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
						panel.add(buttons);
						addTabDialog.add(panel);
						addTabDialog.showRelativeTo((Button)event.getSource());
					}
				});
			}
		    
		    // Return the content
		    if(tabPanel.getWidgetCount() > 0) {
		    	if(tabToBeSelected != -1)
		    		tabPanel.selectTab(tabToBeSelected);
		    	else 
		    		tabPanel.selectTab(0);
		    }
		    	
		    
		    ResizeLayoutPanel resizePanel = new ResizeLayoutPanel();
		    resizePanel.setPixelSize(900, 520);
		    resizePanel.setWidget(tabPanel);
		    
		    holdingPanel.setStyleName("holdingPanel");
			holdingPanel.add(headerWidget);
			if(toolsPanel != null)
				holdingPanel.add(toolsPanel);
			holdingPanel.add(resizePanel);
			if(addTab != null)
				holdingPanel.add(addTab);
		}
		
	}
	
	private UrlSplitted decodeUrl(String url) {
		String[] values = url.split("/");
		UrlSplitted urlInfo = new UrlSplitted();
		urlInfo.user = values[0];
		if(values.length > 1) {
			try {
				urlInfo.tab = Long.valueOf(values[1]);
			} catch (NumberFormatException e) {
				Window.alert("Tab ID specified in the Url is wrong");
			}
		}
		if(values.length > 2) {
			try {
				urlInfo.post = Long.valueOf(values[2]);
			} catch (NumberFormatException e) {
				Window.alert("Post ID specified in the Url is wrong");
			}
		}
		
		return urlInfo;
	}

	@Override
	public void notifyMe(Object arg) {
		// TODO Auto-generated method stub
		String newTheme = (String)arg;
		if(newTheme != null) {
			RootPanel.get().removeStyleName(theme);
			
			this.theme = newTheme;
			
			tabPanel.setStylePrimaryName(theme+"-tabpanel");
			RootPanel.get().addStyleName(theme);
		}
	}
}

class UrlSplitted {
	String user;
	Long tab;
	Long post;
}